﻿using System;
using System.Collections;
using System.Threading.Tasks;
using CzfSDK;

namespace Test
{
	public class TestProto : CzfSDK.CzfProto
	{
		public TestProto (int zipLv):base(zipLv)
		{
			this.defaultMethod = "FrameSync";
			Task.Run (SendFrameDataTask);
		}

		object locks = new object ();
		public void FrameSync(Hashtable ht)
		{
			lock (locks) {
				foreach (var k in ht.Keys) {
					htFrameData [k] = ht [k];
				}
			}
		}

		public void Start()
		{
			lock (locks) {
				var bts = this.Pack ("EventSync", null, 0, new Hashtable ());
				var allClient = CzfNetManager.current.allClient;
				for (int i = 0; i < allClient.Count; i++) {
					var client = allClient [i];
					client.Send (bts);
				}
				Console.WriteLine ("Send count:" + allClient.Count);
			}
		}


		Hashtable htFrameData = new Hashtable();
		void SendFrameDataTask()
		{
			while (true) {
				try{
					byte[] bts;
					lock (locks) {
						bts = this.Pack("SyncCallBack", null,0,htFrameData);
						htFrameData = new Hashtable();
					
						var allClient = CzfNetManager.current.allClient;
						for(int i=0;i<allClient.Count;i++)
						{
							var client = allClient[i];
							client.Send(bts);
						}
					}
					Task.Delay(20*5).Wait();
				}catch(Exception e){
					CzfSDK.CzfLog.Error ("SendFrameDataTask", e);
				}
			}
		}
	}
}

